﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Manon.Core.Extensions
{
    /// <summary>
    /// 随机数生成
    /// </summary>
    public class RandomCode : IRandomCode
    {
        private const string Letters = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";
        private const string Numbers = "1,2,3,4,5,6,7,8,9";

        /// <summary>
        /// 异步随机生成指定位数随机数  默认4位
        /// </summary>
        /// <param name="codeLength"></param>
        /// <returns></returns>
        public Task<string> GenerateOnlyNumberAsync(int codeLength = 4)
        {
            string number = GenerateOnlyNumber(codeLength);
            return Task.FromResult(number);
        }

        /// <summary>
        /// 异步随机生成指定位数编码 默认4位
        /// </summary>
        /// <param name="codeLength"></param>
        /// <returns></returns>
        public Task<string> GenerateCodeAsync(int codeLength = 4)
        {
            string number = GenerateCode(codeLength);
            return Task.FromResult(number);
        }

        /// <summary>
        /// 随机生成指定位数随机数  默认4位
        /// </summary>
        /// <param name="codeLength"></param>
        /// <returns></returns>
        public string GenerateOnlyNumber(int codeLength = 4)
        {
            var array = Numbers.Split(new[] { ',' });

            var random = new Random();

            var temp = -1;

            var captcheCode = string.Empty;

            for (int i = 0; i < codeLength; i++)
            {
                if (temp != -1)
                    random = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));

                var index = random.Next(array.Length);

                if (temp != -1 && temp == index)
                    return GenerateOnlyNumber(codeLength);

                temp = index;

                captcheCode += array[index];
            }

            return captcheCode;
        }

        /// <summary>
        /// 随机生成指定位数编码 默认4位
        /// </summary>
        /// <param name="codeLength"></param>
        /// <returns></returns>
        public string GenerateCode(int codeLength = 4)
        {
            var array = Letters.Split(new[] { ',' });

            var random = new Random();

            var temp = -1;

            var captcheCode = string.Empty;

            for (int i = 0; i < codeLength; i++)
            {
                if (temp != -1)
                    random = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));

                var index = random.Next(array.Length);

                if (temp != -1 && temp == index)
                    return GenerateCode(codeLength);

                temp = index;

                captcheCode += array[index];
            }

            return captcheCode;
        }
    }
}
